""" 目的:
fix 示例3.1_crypto_AES_对称加密.py, 重复初始化 AES.new(self.key, AES.MODE_CBC, self.iv)
加快运行速度

"""

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

# 密钥必须为16、24或32字节长（对应AES-128、AES-192或AES-256）
key = get_random_bytes(32)  # 生成随机密钥
iv = get_random_bytes(16)  # 初始化向量 (IV)，对于CBC模式来说也是必需的
msg = b"hello world; this is a secret message"


class AES_encrypt:
    def __init__(self, key, iv):
        self.key = key
        self.iv = iv
        self.aes_encrypt = AES.new(self.key, AES.MODE_CBC, self.iv)
        self.aes_decrypt = AES.new(self.key, AES.MODE_CBC, self.iv)

    # 加密
    def encrypt(self, msg):
        aes_impl = self.aes_encrypt
        encrypt_msg = aes_impl.encrypt(pad(msg, AES.block_size))
        return encrypt_msg

    # 解密
    def decrypt(self, encrypted_hex):
        aes_impl = self.aes_decrypt
        decrypt_msg = unpad(aes_impl.decrypt(encrypted_hex), AES.block_size)
        return decrypt_msg


if __name__ == "__main__":
    aes = AES_encrypt(key, iv)
    encrypt_msg = aes.encrypt(msg)
    decrypt_msg = aes.decrypt(encrypt_msg)
    print("加密数据", encrypt_msg)
    print("解密数据", decrypt_msg)

    # 重复加密
    msg += b'123456789'
    encrypt_msg = aes.encrypt(msg)
    decrypt_msg = aes.decrypt(encrypt_msg)
    print("--2 加密数据", encrypt_msg)
    print("--2 解密数据", decrypt_msg)

""" 结果:
加密数据 b'\xf7\xe1S\xaf}\xfdf9\xcf\xdbym\xdf\x87\x9e\xd1\x10\xab\xa7\xd3.\xc7\xd2f\xa6\xc7\xce35\x83\xa2E}\x04\xb3\x07\xbbc\x82\xabJ\x1d\x1fE\x8fB\xe4\x15'
解密数据 b'hello world; this is a secret message'
--2 加密数据 b'\xba\xb3\xf1\x98\tZ\x1b\x8dVW\r\x1f\xf1m\xd2iNts\x07\xd7\x18\x89c!Br\xceN\x1e\x10\xaf\x88\x19iO.8\xe2\x17\x0e\xbc\x1a\x01\xcd5h\xe4'
--2 解密数据 b'hello world; this is a secret message123456789'
"""
